package util;

import java.util.HashMap;
import java.util.Map;

/**
 * @author oleksandr.bezhan oleksandr.bezhan@d8corp.com
 * 
 *         Apr 19, 2012
 */
public class ModelUtil {
    private static Map<String, String> translitMap = new HashMap<String, String>();
    static {
        ModelUtil.translitMap.put("а", "a");
        ModelUtil.translitMap.put("б", "b");
        ModelUtil.translitMap.put("в", "v");
        ModelUtil.translitMap.put("г", "g");
        ModelUtil.translitMap.put("д", "d");
        ModelUtil.translitMap.put("е", "e");
        ModelUtil.translitMap.put("ё", "yo");
        ModelUtil.translitMap.put("ж", "zh");
        ModelUtil.translitMap.put("з", "z");
        ModelUtil.translitMap.put("и", "i");
        ModelUtil.translitMap.put("й", "j");
        ModelUtil.translitMap.put("к", "k");
        ModelUtil.translitMap.put("л", "l");
        ModelUtil.translitMap.put("м", "m");
        ModelUtil.translitMap.put("н", "n");
        ModelUtil.translitMap.put("о", "o");
        ModelUtil.translitMap.put("п", "p");
        ModelUtil.translitMap.put("р", "r");
        ModelUtil.translitMap.put("с", "s");
        ModelUtil.translitMap.put("т", "t");
        ModelUtil.translitMap.put("у", "u");
        ModelUtil.translitMap.put("ф", "f");
        ModelUtil.translitMap.put("х", "h");
        ModelUtil.translitMap.put("ц", "c");
        ModelUtil.translitMap.put("ч", "ch");
        ModelUtil.translitMap.put("ш", "sh");
        ModelUtil.translitMap.put("щ", "sch");
        ModelUtil.translitMap.put("ь", "");
        ModelUtil.translitMap.put("ы", "y");
        ModelUtil.translitMap.put("ъ", "");
        ModelUtil.translitMap.put("э", "ye");
        ModelUtil.translitMap.put("ю", "yu");
        ModelUtil.translitMap.put("я", "ya");
        ModelUtil.translitMap.put(" ", "-");
    }

    public static String translit(String str) {
        return translit(str, false);
    }

    public static String translit(String str, boolean saveRegisterCase) {
        StringBuilder translit = new StringBuilder();

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            String charTranslit = ModelUtil.translitMap.get(String.valueOf(c).toLowerCase());
			if (charTranslit == null) {
				charTranslit = String.valueOf(c);
			}

            if (saveRegisterCase) {
                // upper case transformation
                if (Character.isUpperCase(c)) {
                    if (charTranslit.length() > 1) {
                        charTranslit = charTranslit.substring(0, 1).toUpperCase() + charTranslit.substring(1);
                    } else {
                        charTranslit = charTranslit.toUpperCase();
                    }
                }
            }

            translit.append(charTranslit);
        }

        return translit.toString();
    }
}
